<template>
  <view class="login-wrapper">
    <!-- 顶部背景 -->
    <view class="login-header">
      <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
      <view class="header-content">
        <!-- <image class="logo" src="/static/images/logo.png" mode="aspectFit"></image> -->
      </view>
    </view>

    <!-- 登录表单 -->
    <view class="login-form">
      <view class="form-item">
        <uni-icons type="person" size="20" color="#999"></uni-icons>
        <input type="text" v-model="form.name" placeholder="请输入账号" maxlength="11" class="input" confirm-type="next" />
        <uni-icons v-if="form.name" type="clear" size="16" color="#999" @click="form.name = ''"></uni-icons>
      </view>

      <view class="form-item">
        <uni-icons type="locked" size="20" color="#999"></uni-icons>
        <input :password="!showPassword" v-model="form.password" placeholder="请输入密码" class="input" confirm-type="done" />
        <uni-icons :type="showPassword ? 'eye-filled' : 'eye-slash-filled'" size="20" color="#999" @click="togglePasswordVisibility"></uni-icons>
      </view>

      <!-- 验证码输入框 -->
      <view class="form-item code-item">
        <img src="/static/icon/verification.png" alt="" class="code-icon" />
        <input type="text" v-model="form.verificationCode" placeholder="请输入验证码" class="input code-input" confirm-type="done" />
        <view class="code-image-wrapper" @click="resetCodeImg">
          <image :src="codeImgSrc" class="code-image" mode="aspectFit"></image>
        </view>
      </view>

      <view class="form-actions">
        <label class="remember-pwd">
          <checkbox :checked="rememberPwd" @tap="rememberPwd = !rememberPwd" color="#ffc903" style="transform: scale(0.7)" />
          <text>记住密码</text>
        </label>
      </view>

      <button class="login-btn" :disabled="!form.name || !form.password || !form.verificationCode" @click="handleLogin">登 录</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { loginAPI, getVerificationCodeAPI } from '@/api/login'
import { setLoginInfoStorageSync } from '@/utils/storageSync'

// 获取状态栏高度
const statusBarHeight = ref(0)

// 验证码图片地址
const codeImgSrc = ref('')

onMounted(() => {
  // #ifdef MP-WEIXIN
  const windowInfo = wx.getWindowInfo()
  statusBarHeight.value = windowInfo.statusBarHeight
  // #endif

  // 初始化验证码
  resetCodeImg()

  // 获取记住的账号密码
  const rememberedAccount = uni.getStorageSync('rememberedAccount')
  if (rememberedAccount) {
    form.name = rememberedAccount.name
    form.password = rememberedAccount.password
    rememberPwd.value = true
  }
})

// 表单数据
const form = reactive({
  name: '',
  password: '',
  codeKey: '',
  verificationCode: ''
})

// 控制密码显示
const showPassword = ref(false)

// 记住密码
const rememberPwd = ref(false)

// 刷新验证码
const resetCodeImg = () => {
  const codeKey = Math.random()
  form.codeKey = codeKey
  codeImgSrc.value = getVerificationCodeAPI(codeKey)
}

// 处理登录
const handleLogin = async () => {
  // 验证账号格式
  if (!/^[a-zA-Z0-9]+$/.test(form.name)) {
    uni.showToast({
      title: '请输入正确的账号',
      icon: 'none'
    })
    resetCodeImg()
    return
  }

  // 验证密码长度
  if (form.password.length < 5) {
    uni.showToast({
      title: '密码不能少于5位',
      icon: 'none'
    })
    resetCodeImg()
    return
  }

  // 验证验证码
  if (!form.verificationCode || form.verificationCode.trim() === '') {
    uni.showToast({
      title: '请输入验证码',
      icon: 'none'
    })
    resetCodeImg()
    return
  }

  // 显示加载提示
  uni.showLoading({
    title: '登录中...'
  })

  // 执行登录
  const loginRes = await loginAPI(form).catch(() => {
    uni.hideLoading()
    uni.showToast({
      title: '登录失败，请检查网络',
      icon: 'none'
    })
    resetCodeImg()
    return false
  })

  // 隐藏加载提示
  uni.hideLoading()

  if (!loginRes) return

  if (loginRes.code === 0 && loginRes.data) {
    // 保存登录信息到本地存储
    const { expireTime, token, reToken, reExpireTime } = loginRes.data

    setLoginInfoStorageSync(expireTime, token, reToken, reExpireTime)

    // 处理记住密码
    if (rememberPwd.value) {
      uni.setStorageSync('rememberedAccount', {
        name: form.name,
        password: form.password
      })
    } else {
      uni.removeStorageSync('rememberedAccount')
    }

    // 登录成功提示
    uni.showToast({
      title: '登录成功',
      icon: 'success',
      duration: 1500
    })

    // 延迟跳转到首页
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    }, 1500)
  } else {
    // 登录失败，刷新验证码
    resetCodeImg()
    uni.showToast({
      title: loginRes.msg || '登录失败，请重试',
      icon: 'none'
    })
  }
}

// 跳转注册
const handleRegister = () => {
  uni.navigateTo({
    url: '/pages/register/index'
  })
}

// 忘记密码
const handleForgetPwd = () => {
  uni.navigateTo({
    url: '/pages/forget-password/index'
  })
}

// 切换密码显示状态
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}
</script>

<style lang="scss" scoped>
.login-wrapper {
  min-height: 100vh;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.login-header {
  background: linear-gradient(180deg, #3bb7f8 0%, #fff 100%);
  padding-bottom: 60rpx;

  .header-content {
    padding: 60rpx;
    text-align: center;

    .logo {
      width: 120rpx;
      height: 120rpx;
      margin-bottom: 20rpx;
    }

    .title {
      font-size: 48rpx;
      color: #333;
      font-weight: bold;
      margin-right: 16rpx;
      margin-bottom: 16rpx;
    }

    .subtitle {
      font-size: 28rpx;
      color: #666;
    }
  }
}

.login-form {
  padding: 40rpx 60rpx;
  margin-top: -40rpx;
  background: #fff;
  border-radius: 40rpx 40rpx 0 0;
  flex: 1;

  .form-item {
    display: flex;
    align-items: center;
    height: 100rpx;
    background-color: #fbfbfb;
    border-radius: 50rpx;
    padding: 0 30rpx;
    margin-bottom: 30rpx;

    .input {
      flex: 1;
      height: 100%;
      padding: 0 20rpx;
      font-size: 28rpx;
    }

    &.code-item {
      .code-icon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 0;
      }

      .code-input {
        flex: 1;
      }

      .code-image-wrapper {
        position: relative;
        width: 120rpx;
        height: 60rpx;
        margin-left: 20rpx;
        border-radius: 8rpx;
        overflow: hidden;
        background-color: #f5f5f5;
        border: 1rpx solid #e5e5e5;

        .code-image {
          width: 100%;
          height: 100%;
        }

        &:active {
          opacity: 0.8;
        }
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 60rpx;

    .remember-pwd {
      display: flex;
      align-items: center;
      font-size: 26rpx;
      color: #666;
    }

    .forget-pwd {
      font-size: 26rpx;
      color: #666;

      &:active {
        opacity: 0.8;
      }
    }
  }

  .login-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background-color: #3bb7f8;
    color: #333;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 44rpx;
    margin-bottom: 30rpx;

    &:active {
      opacity: 0.8;
    }

    &[disabled] {
      opacity: 0.6;
      background-color: #52bef8 !important;
      color: #333 !important;
    }
  }

  .register-link {
    text-align: center;
    font-size: 26rpx;
    color: #666;

    .link {
      color: #ffc903;
      margin-left: 6rpx;

      &:active {
        opacity: 0.8;
      }
    }
  }
}
</style>
